#include "StdAfx.h"
#include "STCIImageLoader.h"
#include "../sgp/ImageManager.h"

namespace ja2{ namespace sgp
{
	std::string const ImageManager::PCX(".PCX");
	std::string const ImageManager::STCI(".STI");

	ImageManager::ImageManager(void)
	{
		m_ImageLoaderMap[STCI] = std::unique_ptr<IImageLoader>(new STCIImageLoader());
	}

	ImagePtr_t ImageManager::load_image(boost::filesystem::path const &FileName, std::uint_least16_t Flags)
	{
		// Copy the path
		boost::filesystem::path file_name(FileName);
		// Get extension
		std::string ext = boost::algorithm::to_upper_copy(FileName.extension().string());
		// Extension empty, use default internal loader extension
		if(ext.empty())
		{
			JA2_DEBUG_MESSAGE(TOPIC_HIMAGE, DebugManager::DL_2, "No extension given, using default" );
			ext = PCX;
			file_name /= ext;
			
		}
		// Determine if resource exists before creating image structure
		if (!vfs::VirtualFileSystem::instance()->file_exists(file_name))
		{
			std::string const error("Resource file '" + file_name.string() + "' does not exist.");
			JA2_DEBUG_MESSAGE(TOPIC_HIMAGE, DebugManager::DL_2, error.c_str());
			throw RuntimeException(error);
		}
		// Determine type from Extension
		auto it = m_ImageLoaderMap.find(ext);
		if(it == m_ImageLoaderMap.end())
		{
			std::string const error("No extension image loader found for extension '" + ext + "'");
			JA2_DEBUG_MESSAGE(TOPIC_HIMAGE, DebugManager::DL_0, error.c_str());
			throw RuntimeException(error);
		}
		JA2_ASSERT(vfs::VirtualFileSystem::instance()->file_exists(file_name));
		// Get file
		vfs::FileStream_t file(vfs::VirtualFileSystem::instance()->open_file(file_name).open(std::ios_base::binary));
		// Be sure file is valid
		JA2_ASSERT_MESAGE(file, "File not valid.");
		// Load image
		ImagePtr_t p_image = it->second->load_image(file_name.string(), file, Flags);

		return p_image;
	}
} /*sgp*/} /*ja2*/